//
//  BBLoginHomeViewController.m
//  BlockBrowser
//
//  Created by Mac on 2018/3/30.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "BBLoginHomeViewController.h"
#import "BBPhoneLoginViewController.h"
@interface BBLoginHomeViewController ()<WXApiDelegate,TencentSessionDelegate>
@property(nonatomic, strong) TencentOAuth                     *tencentOAuth ;
@end

@implementation BBLoginHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    [self configSubView];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight)];
    header.backgroundColor = [UIColor whiteColor];
   
#define buttonWith  UIScreenWidth - 60
    
    STButton * qqButton = [[STButton alloc] initWithFrame:CGRectMake(30, 80, buttonWith, 50)
                                                     title:@"腾讯QQ一键登录"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:16
                                              cornerRadius:8
                                           backgroundColor:TM_ThemeBackGroundColor
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"qq"]];
    qqButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    qqButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [qqButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedQQLoginButton];
    }];
  //  [header addSubview:qqButton];
    
    STButton * wechatButton = [[STButton alloc] initWithFrame:CGRectMake(30, qqButton.bottom + 30, buttonWith, 50)
                                                    title:@"微信客户端登录"
                                               titleColor:[UIColor whiteColor]
                                                titleFont:16
                                             cornerRadius:8
                                          backgroundColor:TM_ThemeBackGroundColor
                                          backgroundImage:nil
                                                    image:[UIImage imageNamed:@"微信"]];
    wechatButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    wechatButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [wechatButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedWeChatLoginButton];
    }];
 //   [header addSubview:wechatButton];
    
    
    STButton * phoneButton = [[STButton alloc] initWithFrame:CGRectMake(30, wechatButton.bottom + 30, buttonWith, 50)
                                                        title:@"手机号码登录"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:16
                                                 cornerRadius:8
                                              backgroundColor:TM_ThemeBackGroundColor
                                              backgroundImage:nil
                                                        image:[UIImage imageNamed:@"手机"]];
    phoneButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    phoneButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    phoneButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    [phoneButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedPhoneLoginButton];
    }];
    [header addSubview:phoneButton];
    
    self.tableView.tableHeaderView = header;
}
#pragma mark --Action Method
- (void)onSelctedQQLoginButton{
    [SVProgressHUD showWithStatus:@"登录中请稍后"];
    self.tencentOAuth =  [[TencentOAuth alloc] initWithAppId:TencentQQAppid andDelegate:self];
    NSArray * permissions = [NSArray arrayWithObjects:@"get_user_info", @"add_share", nil];
    [self.tencentOAuth authorize:permissions inSafari:NO];
}
- (void)onSelctedWeChatLoginButton{
    [SVProgressHUD showInfoWithStatus:@"微信登录审核中"];
    return;
    //微信登录
    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"BlockBowser" ;
    [WXApi sendReq:req];
}
- (void)onSelctedPhoneLoginButton{
    [self.navigationController pushViewController:[BBPhoneLoginViewController new] animated:YES];
}
#pragma mark --TencentSessionDelegate
- (void)tencentDidLogin{
    
  [self.tencentOAuth getUserInfo];
    
}
- (void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
        [SVProgressHUD showInfoWithStatus:@"用户点击取消按键,主动退出登录"];
    }else{
        [SVProgressHUD showInfoWithStatus:@"其他原因， 导致登录失败"];
    }
}
- (void)getUserInfoResponse:(APIResponse*) response{
    
    NSString * nickName = response.jsonResponse[@"nickname"];
    
    NSString * headimgurl = response.jsonResponse[@"figureurl_2"];
    [self sendLoginTheKingWithOpenId:self.tencentOAuth.openId
                             unionid:self.tencentOAuth.unionid
                            nickname:nickName
                          headimgurl:headimgurl];
    
}
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSLog(@"%@",token);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信登录"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝了微信登录"];
        }
        if (resp.errCode == 0) {
            // [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
            NSString * url =   [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
                                wechatID,
                                wechatSecret,
                                token];
            [self fetchWeChatOpenIdRequestWithUrl:url];
            // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信分享"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信分享"];
        }
        if (resp.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信分享成功"];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        if (pay.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信支付"];
        }
        if (pay.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信支付"];
        }
        if (pay.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信支付成功"];
        }
    }
}
#pragma mark --NetWork Method
- (void)fetchWeChatOpenIdRequestWithUrl:(NSString*)url{
    [SVProgressHUD showWithStatus:@"请稍后"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        if ([dic.allKeys containsObject:@"openid"]) {
            NSString * openid = dic[@"openid"];
            NSString * acceesstoken = dic[@"access_token"];
            NSLog(@"微信登录的Openid%@",openid);
            NSString * url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",acceesstoken,openid];
            [self fecthWechatUserInfoRequestWithUrl:url];
            
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)fecthWechatUserInfoRequestWithUrl:(NSString*)url{
    // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = responseObject;
        if ([dic.allKeys containsObject:@"openid"]) {
            
            NSString * openid = dic[@"openid"];
            NSString * unionid = dic[@"unionid"];
            NSString * nickName = dic[@"nickname"];
            NSString * headimgurl = dic[@"headimgurl"];
            [self sendLoginTheKingWithOpenId:openid unionid:unionid nickname:nickName headimgurl:headimgurl];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
- (void)sendLoginTheKingWithOpenId:(NSString*)openid unionid:(NSString*)unionid nickname:(NSString*)nickname headimgurl:(NSString*)headimgurl{
    

    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (openid.length) {
        [dic setObject:openid forKey:@"openid"];
    }else{
        NSLog(@"openid为空");
        return;
    }
    if (nickname.length) {
        [dic setObject:nickname forKey:@"nickname"];
    }else{
        NSLog(@"nickname为空");
        return;
    }
    
    if (headimgurl.length) {
        [dic setObject:headimgurl forKey:@"headimgurl"];
    }else{
        NSLog(@"headimgurl为空");
        return;
    }
    [dic setObject:@"0" forKey:@"invitation_code"];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/user/otherLogin"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                                                 NSDictionary * modelDIc = [responseObject valueForKey:@"user"];
                                                 BBUserModel * user = [BBUserModel mj_objectWithKeyValues:modelDIc];
                                                 user.openid = openid;
                                                 [[STUserManger defult] updateUserModel:user];
                                                 
                                                 [self.view endEditing:YES];
                                                 [self.navigationController popToRootViewControllerAnimated:YES];
                                                 [[UIApplication sharedApplication].keyWindow st_showAnimationWithType:STAnimationTyperippleEffect duration:2];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

@end
